package com.liyao.windowtest4.controller.wrench;

import com.liyao.windowtest4.controller.UpdateProgramController;
import com.liyao.windowtest4.controller.managementController;
import com.liyao.windowtest4.pojo.Routine;
import com.liyao.windowtest4.pojo.torqueRow;
import com.liyao.windowtest4.pojo.wrenchRow;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-10-30 15:25
 */
public class updateWrenchController implements Initializable {
    public TextField SNText;
    public TextField torqueMinText;
    public TextField wrenchNameText;
    public TextField torqueMaxText;

    private wrenchRow wrenchRow;

    private boolean isAdd=false;

    public boolean isAdd() {
        return isAdd;
    }

    public String newDataLine;

    private String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;


    public void updateWrenchSubmit(ActionEvent actionEvent) throws IOException {
        // 定义要写入的文件路径
        String filePath = configDirPath+"torqueItems.txt"; // 您可以根据需要更改文件路径
        String tempFilePath = filePath + ".tmp";
        String targetCode = this.wrenchRow.getSN();
        InputStream inputStream = new FileInputStream(filePath);

        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine())!= null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件错误："+e);
        }

        // 查找并替换目标行
        List<String> updatedLines = lines.stream()
                .map(line -> {
                    if (line.contains("\"SN\":\"" + targetCode + "\"")) {
                        JSONObject js=JSONObject.fromObject(line);
                        js.put("TorqueName",wrenchNameText.getText());
                        js.put("TorqueMin",torqueMinText.getText());
                        js.put("TorqueMax",torqueMaxText.getText());
                        this.newDataLine=js.toString();
                        return js.toString();
                    }
                    return line;
                })
                .collect(Collectors.toList());

        // 将修改后的内容写回临时文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            for (String line : updatedLines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原始文件
        try {
            Files.deleteIfExists(Paths.get(filePath));
            Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件修改成功！");
            this.isAdd = true; // 假设这里isAdd用于表示是否成功添加了数据（尽管这里是更新）
            Stage stage = (Stage) ((Button) actionEvent.getSource()).getScene().getWindow();
            stage.close();
        } catch (IOException e) {
            e.printStackTrace();
            this.isAdd = false; // 更新失败
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        SNText.setEditable(false);
    }

    public void setDataItem(wrenchRow currentRowItem) {
        this.wrenchRow=currentRowItem;
        SNText.setText(String.valueOf(this.wrenchRow.getSN()));
        torqueMinText.setText(String.valueOf(this.wrenchRow.getTorqueMin()));

        wrenchNameText.setText(String.valueOf(this.wrenchRow.getTorqueName()));
        torqueMaxText.setText(String.valueOf(this.wrenchRow.getTorqueMax()));

    }

    public void updateNetworkSubmit(ActionEvent actionEvent) {
        System.out.println("网关"+this.wrenchRow.getGateway());
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/wrench/updateWrenchNetwork.fxml"));
        Parent bPageRoot = null;
        try {
            bPageRoot = loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateWrenchNetworkController bController = loader.getController();
        // 将数据传递给B页面的控制器
        bController.setDataItem(this.wrenchRow);

        // 创建一个新的Stage或Dialog来显示B页面
        Stage stage = new Stage();
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.initStyle(StageStyle.UTILITY);
        stage.setTitle("配置扳手网络");
        stage.setScene(new Scene(bPageRoot));
        stage.showAndWait();
    }

    public wrenchRow getNewData() {
        System.out.println(newDataLine);
        JSONObject js=JSONObject.fromObject(this.newDataLine);
        wrenchRow wr=new wrenchRow(js.get("SN").toString(),
                js.getString("TorqueName"),
                Double.parseDouble(js.getString("TorqueMin")),
                Double.parseDouble(js.getString("TorqueMax")),
                js.getString("SSID"),
                js.getString("password"),
                js.getString("Host"),
                Integer.parseInt(js.getString("Port")),
                js.getString("SubnetMask"),
                js.getString("gateway"),
                js.getString("addTime"));
        return wr;
    }
}
